﻿using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace library
{
    public partial class book1_in : Form
    {
        public MySqlConnection conn = new DBclass().getConn();
        DataSet ds = new DataSet();
        DataTable dt;
        public book1_in()
        {
            InitializeComponent();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            book_in f = new book_in();
            f.Show();
            this.Close();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.OpenFileDialog fd = new OpenFileDialog();
            if (fd.ShowDialog() == DialogResult.OK)
            {
                string fileName = fd.FileName;
                bind(fileName);
            }
        }
        private void bind(string fileName)
        {

            string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +
                 "Data Source=" + fileName + ";" +
                 "Extended Properties='Excel 8.0; HDR=Yes; IMEX=1'";
            OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", strConn);
            DataSet ds = new DataSet();
            try
            {
                da.Fill(ds);
                dt = ds.Tables[0];
                this.dataGridView1.DataSource = dt;
            }
            catch (Exception err)
            {
                MessageBox.Show("操作失败！" + err.ToString());
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            conn.Open();
            if (dataGridView1.Rows.Count > 0)
            {
                DataRow dr = null;
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    dr = dt.Rows[i];

                    insertToSql(dr);

                }

                conn.Close();
                MessageBox.Show("导入成功！");
            }
            else
            {
                MessageBox.Show("没有数据！");
            }
        }
        private void insertToSql(DataRow dr)
        {
            //excel表中的列名和数据库中的列名一定要对应  
            string ISBN = dr["ISBN"].ToString().Trim();
            string bname = dr["图书名称"].ToString();
            string author = dr["作者"].ToString();
            string price = dr["单价"].ToString();
            string press = dr["出版社"].ToString();
            string pub_time = dr["出版时间"].ToString();
            string type = dr["图书类型"].ToString();

            string sql = "insert into book1_info values('" + ISBN + "','" + bname + "','" + author + "','" + price + "','" + press + "','" + pub_time + "','" + type + "')";
            MySqlCommand cmd = new MySqlCommand(sql, conn);
            cmd.ExecuteNonQuery();

        }
    }
}
